<?php

namespace app\common\model\chat;

use think\Model;

class ChatMessage extends Model
{
    protected $append = ['nickname', 'avatar'];

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id');
    }

    /**
     * 关联群组
     */
    public function group()
    {
        return $this->belongsTo('ChatGroup', 'group_id', 'id');
    }

    /**
     * 获取用户昵称
     */
    public function getNicknameAttr($value, $data)
    {
        return $this->user()->value('nickname') ?? 'AI小助手';
    }

    /**
     * 获取用户头像
     */
    public function getAvatarAttr($value, $data)
    {
        $user_id = $data['user_id'] ?? 0;
        $user = \app\common\model\User::where(['id'=>$user_id])->find();
        $avatar = $user->avatar ?? letter_avatar("AI小助手");
        return $avatar;
    }
}